package com.company.chatRoom;

import com.company.utils.MyException;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Random;

/**
 * @Auther Xue
 * @Date 2021/4/28
 * @Version 1.0
 * @Desc    聊天室客户端
 */
public class ChatClient {
//    客户端使用同一个socket
    private static Socket socket;
    //一个socket下的oos只能有一个oos
    private static boolean isconn = false;
    private static Thread sendThread;
    private static Thread listenThread;
    private static Thread heartThread;
    private static String userName;
    public static void turnOffState(){
        isconn = false;
    }

    public static void main(String[] args) {
        while (!isconn) {
            try {
                connect();
            } catch (Exception e) {
                MyException.logExceptionMessage(e);
                isconn = false;
                closeAllThread();
                System.out.println("正在尝试重新连接...");
            }
        }
    }
    public static void connect() throws Exception {
        socket = new Socket("localhost",9999);
        isconn = true;
        System.out.println("已连上");
        if(isconn){
            if(userName == null){
                userName = "游客"+new Random().nextInt(10000);
            }
            if(sendThread == null){
                sendThread = new Thread(new ClientSend(socket,userName));
            }
            sendThread.start();
            if(listenThread == null){
                listenThread = new Thread(new ClientListen(socket));
            }
            listenThread.start();
            if (heartThread == null){
                heartThread = new Thread(new ClientHeart(socket,userName));
            }
            heartThread.start();
        }
    }
    public static void reconnect() throws Exception {
        while(!isconn) {
            System.out.println("正在尝试重新连接");
            connect();
            Thread.sleep(10000);
        }
    }
    public static void closeAllThread(){
        if(listenThread.isAlive()){
            listenThread.interrupt();
            System.out.println("listenThread断开连接");
        }
        if(sendThread.isAlive()){
            sendThread.interrupt();
            System.out.println("sendThread断开连接");
        }
        if(heartThread.isAlive()){
            heartThread.interrupt();
            System.out.println("heartThread断开连接");
        }
    }

}
